package org.jsbd.boss.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import edu.hziee.common.lang.StringUtil;

public class GetIpAddress {
    private static Logger logger = LoggerFactory.getLogger(GetIpAddress.class);

    public static String getInfo(String srcUrl, int timeoutMils) throws IOException {

        URL url = new URL(srcUrl);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setReadTimeout(timeoutMils);

        InputStreamReader inputReader = new InputStreamReader(httpconn.getInputStream());
        BufferedReader bufReader = new BufferedReader(inputReader);

        String tmpLine = "";
        StringBuffer contentBuffer = new StringBuffer();

        while ((tmpLine = bufReader.readLine()) != null) {
            contentBuffer.append(tmpLine);
        }

        bufReader.close();
        httpconn.disconnect();
        return contentBuffer.toString();
    }
    
    public static String getInfo(String srcUrl, int timeoutMils, String Para, String headerStr) throws IOException {
        URL url = new URL(srcUrl);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        if(!StringUtil.isBlank(headerStr) && !StringUtil.isBlank(Para)){
            httpconn.addRequestProperty(Para, headerStr);
        }
        httpconn.setReadTimeout(timeoutMils);

        InputStreamReader inputReader = new InputStreamReader(httpconn.getInputStream());
        BufferedReader bufReader = new BufferedReader(inputReader);

        String tmpLine = "";
        StringBuffer contentBuffer = new StringBuffer();

        while ((tmpLine = bufReader.readLine()) != null) {
            contentBuffer.append(tmpLine);
        }

        bufReader.close();
        httpconn.disconnect();
        return contentBuffer.toString();
    }

    public static BufferedReader getReader(String srcUrl, int timeoutMils) throws IOException {
        URL url = new URL(srcUrl);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setReadTimeout(timeoutMils);

        InputStreamReader inputReader = new InputStreamReader(httpconn.getInputStream());
        BufferedReader bufReader = new BufferedReader(inputReader);
        return bufReader;
    }
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param,int timeoutMils) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(timeoutMils);
            conn.setReadTimeout(timeoutMils);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	logger.error("连接错误：", e.getMessage());
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
    
    // POST
    public static String getInfoByPost(String urlStr, int timeoutMils) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            URL url = new URL(urlStr);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);

            urlCon.setRequestProperty("Content-Type", "text/xml");  
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }
 // POST
    public static String getInfoByPost(String urlStr, String xml, int timeoutMils) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] xmlData = xml.getBytes();
        try {
//        	Properties props = System.getProperties();  
//            props.setProperty("proxySet", "true");  
//            props.setProperty("http.proxyHost", "114.253.250.56");  
//            props.setProperty("http.proxyPort","8888");
            URL url = new URL(urlStr);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);

            urlCon.setRequestProperty("Content-Type", "text/xml");  
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }
    
    // POST
    public static String getInfoByPost2(String urlStr, String xml, int timeoutMils, boolean isXml) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] xmlData = xml.getBytes();
        try {
            URL url = new URL(urlStr);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);

            if(isXml){
                urlCon.setRequestProperty("Content-Type", "text/xml");    	
            }
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }
    
    public static String getInfoByJsonPost(String urlStr, String jsonString, int timeoutMils) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] jsonData = jsonString.getBytes();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);
            urlCon.setRequestProperty("Content-Type", "application/json");
            urlCon.setRequestProperty("Content-length", String.valueOf(jsonData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(jsonData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }
    
    public static String getInfoByJsonPost(String urlStr, String jsonString,String contentType, String contentType2, String charset, int timeoutMils) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] jsonData = jsonString.getBytes();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);
            
            urlCon.setRequestProperty("ContentType", contentType);
            urlCon.setRequestProperty("Content-type",contentType2);
            urlCon.setRequestProperty("charset", charset);
            urlCon.setRequestProperty("Content-Length",
					String.valueOf(jsonString.length()));
			urlCon.setRequestProperty(
							"User-Agent",
							"Mozilla/5.0 (Windows NT //5.1)AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.46 Safari/535.11");
			
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(jsonData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }    
    
    public static String getInfoByJsonPost(String urlStr, Map<String,Object> paramMap, int timeoutMils) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StringBuffer params = new StringBuffer();
        for (Iterator<Entry<String, Object>> iter = paramMap.entrySet().iterator(); iter.hasNext();){
        	Entry<String, Object> element = iter.next();
            params.append(element.getKey().toString());
            params.append("=");
            params.append(element.getValue().toString());
            params.append("&");
        }

        if (params.length() > 0){
            params = params.deleteCharAt(params.length() - 1);
        }
        
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);
            urlCon.setRequestProperty("Content-Type", "application/Json");
            urlCon.setRequestProperty("Content-length", String.valueOf(params.length()));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(params.toString().getBytes());
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];
            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }
    
    public static Map<String,String> getInfoByMapAndPost(String urlStr, Map<String,String> paramMap, int timeoutMils) {
    	Map<String,String> resultMap=new HashMap<String,String>();
    	List<NameValuePair> paramList = new ArrayList <NameValuePair>();  
    	for(Entry<String, String> param:paramMap.entrySet()){
    		paramList.add(new BasicNameValuePair(param.getKey(),param.getValue()));
    	}
    	HttpClient httpclient =new DefaultHttpClient();
    	HttpPost post=new HttpPost(urlStr);
    	try{
    		UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList, "UTF-8");
            urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutMils); 
            httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutMils);
            post.setEntity(urlEncodedFormEntity);
     	    HttpResponse resultResponse = httpclient.execute(post);
     	    if(resultResponse.getStatusLine()==null){
     	    	resultMap.put("code", "-101");
     	    	return resultMap;
     	    }
     	    resultMap.put("code", resultResponse.getStatusLine().getStatusCode()+"");
     	    resultMap.put("msg", EntityUtils.toString(resultResponse.getEntity(),"utf-8"));
     	  
    	}catch(Exception e){
    		String paramStr=null;
    		if(paramMap!=null){
    			paramStr=paramMap.toString();
    		}
    		logger.error("getInfoByMapAndPost error and url is [{}] and param is [{}]",new Object[]{urlStr,paramStr,e});
    	}finally{
    		post.releaseConnection();
    	}
    	return resultMap;
    }

    /**
     * 
     * 带头信息的json方式请求 <br><pre>
     * 编写者：<a href="mailto:yuanmiao@zhexinit.com" >袁淼</a>
     * 创建时间：2016年5月4日 下午7:52:30 </pre>
     * @param urlStr
     * @param paramMap
     * @param contentType
     * @param timeoutMils
     * @param headers
     * @return
     */
    public static Map<String,String> getInfoByMapAndJson(String urlStr, Map<String,Object> paramMap, String contentType, int timeoutMils, final Map<String, String> headers) {
    	Map<String,String> resultMap=new HashMap<String,String>();
//    	List<NameValuePair> paramList = new ArrayList <NameValuePair>();  
//    	for(Entry<String, Object> param:paramMap.entrySet()){
//    		paramList.add(new BasicNameValuePair(param.getKey(), param.getValue().toString()));
//    	}
    	HttpClient httpclient =new DefaultHttpClient();
    	HttpPost post=new HttpPost(urlStr);
    	try{
//    		UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList, "UTF-8");
//            urlEncodedFormEntity.setContentType(contentType);
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutMils); 
            httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutMils);
            
            StringEntity se = new StringEntity(JSON.toJSONString(paramMap), "UTF-8");
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", contentType));
            post.setEntity(se);
            
            if (headers != null) {
                Set<Map.Entry<String, String>> entrySet = headers.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                	post.setHeader(entry.getKey(), entry.getValue());
                }
            }
     	    HttpResponse resultResponse = httpclient.execute(post);
     	    if(resultResponse.getStatusLine()==null){
     	    	resultMap.put("code", "-101");
     	    	return resultMap;
     	    }
     	    resultMap.put("code", resultResponse.getStatusLine().getStatusCode()+"");
     	    resultMap.put("msg", EntityUtils.toString(resultResponse.getEntity(),"utf-8"));
     	  
    	}catch(Exception e){
    		String paramStr=null;
    		if(paramMap!=null){
    			paramStr=paramMap.toString();
    		}
    		logger.error("getInfoByMapAndPost error and url is [{}] and param is [{}]",new Object[]{urlStr,paramStr,e});
    	}finally{
    		post.releaseConnection();
    	}
    	return resultMap;
    }    

	public static String getMobileInfoByPost(String urlStr, String xml, int timeoutMils, String accept, String contentType, String orginalClientIp) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] xmlData = xml.getBytes();
        try {
//        	Properties props = System.getProperties();  
//            props.setProperty("proxySet", "true");  
//            props.setProperty("http.proxyHost", "114.253.250.56");  
//            props.setProperty("http.proxyPort","8888");
        	if(StringUtil.isBlank(orginalClientIp)){
        		orginalClientIp = "114.253.250.56";
        	}
        	
            URL url = new URL(urlStr);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);

            urlCon.setRequestProperty("Content-Type", contentType);
            urlCon.setRequestProperty("Content-Length", String.valueOf(xmlData.length));
            urlCon.setRequestProperty("Accept", accept);
            urlCon.setRequestProperty("Connection", "Keep-Alive");
//            urlCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");            
            urlCon.setRequestProperty("X-Forwarded-For", orginalClientIp);//这个优先级最高
//			urlCon.setRequestProperty("X-Real-IP", orginalClientIp);
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
	}
	
	public static String getMobileLoginInfoByPost2(String url, String param, int timeoutMils, String acceptEncoding, String contentType, String orginalClientIp) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	if(StringUtil.isBlank(orginalClientIp)){
        		orginalClientIp = "114.253.250.56";
        	}
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept-Encoding", acceptEncoding);
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("X-Forwarded-For", orginalClientIp);//这个优先级最高
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(timeoutMils);
            conn.setReadTimeout(timeoutMils);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param.getBytes());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("发送 POST 请求出现异常！" + e.getMessage(), e);
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
            	logger.error(ex.getMessage(), ex);
            }
        }
        return result;
    }   
	
	/**
	 * 
	 * getResponseOfJsonByPost:TODO 请描述该方法是做什么用途的
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param url
	 * @param headers	
	 * 				不同的方法可能请求的header设置不同，所以在封装json请求的时候需要在接口里面自定义
	 * 				比如
	 * 				"Content-Type":"application/json;charset=UTF-8"
	 * 				"Content-Type":"text/html;charset=utf-8" "Content-Type":"application/x-www-form-urlencoded"
	 *				1、传递参数类型是 str="json={"name":"xpc"}" "Content-Type":"text/html;charset=utf-8" "Content-Type":"application/x-www-form-urlencoded"
	 *				2、传递参数类型是 str="{"name":"xpc"}"      "Content-Type":"application/json;charset=UTF-8"
	 * @param jsonStr
	 * @param timeoutMils
	 * @return
	 */
	public static String getResponseOfJsonByPost(String url, Map<String, String> headers, String jsonStr, int timeoutMils){

		DataOutputStream out = null;
		HttpURLConnection connection = null;
		String data = null;
		try {
			URL postUrl = new URL(url);
		    connection = (HttpURLConnection) postUrl.openConnection();
			// 打开读写属性，默认均为false
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// 设置请求方式，默认为GET
			connection.setRequestMethod("POST");
			// Post 请求不能使用缓存
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setConnectTimeout(timeoutMils);
			connection.setReadTimeout(timeoutMils);
			if(headers != null && !headers.isEmpty()){
				String[] keys = headers.keySet().toArray(new String[0]);
				for(String key : keys){
					connection.setRequestProperty(key, headers.get(key));
				}
			}
		    out = new DataOutputStream(connection.getOutputStream());
			out.write(jsonStr.getBytes());
			out.flush();
			data = out.toString();
		} catch (Exception e) {
			logger.error("请求错误!",e);
		} finally{
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
				}
			}
			if(connection != null){
				connection.disconnect();
			}
		}
		return data;
	
	}
	
	
	/**
	 * 
	 * getResponseOfJsonByPost:根据json请求返回结果
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @param url
	 * @param headers	
	 * @param params
	 * @param timeoutMils
	 * @return
	 */
	public static String getResponseOfJsonByPost(String url, Map<String, String> headers, Map<String, String> params, int timeoutMils){
		DataOutputStream out = null;
		HttpURLConnection connection = null;
		String data = null;
		try {
			URL postUrl = new URL(url);
		    connection = (HttpURLConnection) postUrl.openConnection();
			// 打开读写属性，默认均为false
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// 设置请求方式，默认为GET
			connection.setRequestMethod("POST");
			// Post 请求不能使用缓存
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setConnectTimeout(timeoutMils);
			connection.setReadTimeout(timeoutMils);
			if(headers != null && !headers.isEmpty()){
				String[] keys = headers.keySet().toArray(new String[0]);
				for(String key : keys){
					connection.setRequestProperty(key, headers.get(key));
				}
			}
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			connection.setRequestProperty("Accept", "application/json");
		    out = new DataOutputStream(connection.getOutputStream());
			String content = JSONObject.toJSONString(params);
			out.write(content.getBytes());
			out.flush();
			data = out.toString();
		} catch (Exception e) {
			logger.error("请求错误!",e);
		} finally{
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
				}
			}
			if(connection != null){
				connection.disconnect();
			}
		}
		return data;
	}
	
	public static String getMobileLoginInfoByPost(String urlStr, String param, int timeoutMils, String acceptEncoding, String contentType, String orginalClientIp) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] xmlData = param.getBytes();
        try {
        	if(StringUtil.isBlank(orginalClientIp)){
        		orginalClientIp = "114.253.250.56";
        	}
        	
            URL url = new URL(urlStr);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);

            urlCon.setRequestProperty("Content-Type", contentType);
            urlCon.setRequestProperty("Content-Length", String.valueOf(xmlData.length));
            urlCon.setRequestProperty("Accept-Encoding", acceptEncoding);
            urlCon.setRequestProperty("Connection", "Keep-Alive");
            urlCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
//            urlCon.setRequestProperty("X-Forwarded-For", orginalClientIp);//这个优先级最高
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }
	
	
    public static String getResInfoByPost(String urlStr, String param, int timeoutMils, final Map<String, String> headers) {
        DataInputStream input = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] xmlData = param.getBytes();
        try {
            
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setConnectTimeout(timeoutMils);
            urlCon.setReadTimeout(timeoutMils);

            urlCon.setRequestMethod("POST");
            if (headers != null) {
                Set<Map.Entry<String, String>> entrySet = headers.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    urlCon.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            input = new DataInputStream(urlCon.getInputStream());
            byte[] bufferByte = new byte[256];

            int i = -1;
            while ((i = input.read(bufferByte)) > -1) {
                out.write(bufferByte, 0, i);
                out.flush();
            }
        } catch (Exception e) {
            logger.error("连接错误：", e);
        }
        return out.toString();
    }	
	
	
	/**
	 *
	 * POST表单请求，支持302跳转重定向 <br><pre>
	 * 方法getInfoByMapAndPostWithRedirect的详细说明 <br>
	 * 编写者：李晓亮
	 * 创建时间：2015年8月10日 下午5:57:00 </pre>
	 * @param 参数名 说明
	 * @return Map<String,String> 说明
	 * @throws 异常类型 说明
	 */
	public static Map<String,String> getInfoByMapAndPostWithRedirect(String urlStr, Map<String,String> paramMap, int timeoutMils) {
        Map<String,String> resultMap=new HashMap<String,String>();
        List<NameValuePair> paramList = new ArrayList <NameValuePair>();  
        for(Entry<String, String> param:paramMap.entrySet()){
            paramList.add(new BasicNameValuePair(param.getKey(),param.getValue()));
        }
        
        HttpPost post=new HttpPost(urlStr);
        try{
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList, "UTF-8");
            urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            
            post.setEntity(urlEncodedFormEntity);
            HttpResponse resultResponse = new DefaultHttpClient().execute(post);
            if(resultResponse.getStatusLine()==null){
                resultMap.put("code", "-101");
                return resultMap;
            }
            resultMap.put("code", resultResponse.getStatusLine().getStatusCode()+"");
            resultMap.put("msg", EntityUtils.toString(resultResponse.getEntity(),"utf-8"));
            if(resultResponse.getStatusLine().getStatusCode()==302){
                String redirectUrl = resultResponse.getHeaders("Location")[0].getValue();
                String resultString = getInfo(redirectUrl, timeoutMils);
                resultMap.put("msg",resultString);
            }
          
        }catch(Exception e){
            e.printStackTrace();
        }finally{
        	post.releaseConnection();
        }
        return resultMap;
    }
    
	/**
	 * 
	 * getResponseCookie:获取请求返回的cookie
	 * 
	 * @author <a href="mailto:wulei@zhexinit.com" >吴磊</a>
	 * @param srcUrl
	 * @param timeoutMils
	 * @return
	 */
	public static String getResponseCookie(String srcUrl, int timeoutMils) {
		try {
			HttpGet post = new HttpGet(srcUrl);
			HttpResponse resultResponse = new DefaultHttpClient().execute(post);
			if (resultResponse.getStatusLine().getStatusCode() == 200) {
				Header[] headerArr = resultResponse.getAllHeaders();
				for (Header header : headerArr) {
					if (header.getName().equals("Set-Cookie")) {
						return header.getValue().substring(0, header.getValue().indexOf(";"));
					}
				}
			}
		} catch (Exception e) {
			logger.error("获取返回cookie出错", e);
		}
		return null;
	}
}
